﻿namespace Pp.Repository
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Core;
    using Core.Extentions;
    using Core.File;
    using Domain.Model;
    using Globalization;
    using NHibernate;
    using NHibernate.Criterion;

    public class ProfileFollowRepository : BaseRepository<ProfileFollow>
    {
        private UserRepository _userRepository;
        public ProfileFollowRepository(ISession session, HttpServerUtilityBase serverUtilityBase)
            : base(session, serverUtilityBase)
        {
            _userRepository = new UserRepository(session, serverUtilityBase);
        }

        public Result<int> Follow(Guid? userId, string followerName)
        {
            var follower = _userRepository.GetByUsername(followerName);
            var user = _userRepository.Get(userId);
            var follow = new ProfileFollow
                             {
                                 Follower = follower,
                                 User = user,
                                 IsPassive = false,
                                 Reason = ""
                             };
            Save(follow);
            SendMail(CreateMail(Res.Information_project_follow, MailType.ProfileFollow, new List<MailModel>
                                                                                            {
                                                                                                new MailModel("Username",follower.GetFullName()),
                                                                                                new MailModel("FollowCount",user.TheyFollows.Count.ToString())
                                                                                            }, user.MailAdress).Data);
            return Result<int>.AsSuccess(user.TheyFollows.Count);
        }

        public Result<int> CancelFollow(Guid? userId, string followerName)
        {
            var follow =  Get(userId, followerName);
            Delete(follow);
            return Result<int>.AsSuccess(follow.User.TheyFollows.Count);
        }

        private ProfileFollow Get(Guid? projectId, string followerName)
        {
            var follow = BaseCriteria
                .CreateAlias("User", "u")
                .CreateAlias("Follower", "f")
                .Add(Restrictions.Eq("u.Id", projectId))
                .Add(Restrictions.Eq("f.Username", followerName)).List<ProfileFollow>();
            return follow.ToList().FirstOrDefault();
        }
    }
}